package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

// 声明读写文件的路径
var (
	path         = "D:\\File\\ChromeDownLoad\\说明.txt"
	writePath    = "D:\\Application\\WorkSpace\\GoLang\\demo-go\\obj\\os\\file.txt"
	srcImagePath = "D:\\Application\\WorkSpace\\GoLang\\demo-go\\obj\\os\\java.png"
	dstImagePath = "D:\\Application\\WorkSpace\\GoLang\\demo-go\\obj\\os\\java_copy.png"
)

func main() {
	// 通过缓存一行一行地读取
	//readFileByBuffer(path)

	// 整个文件都读取出来,适用于文件不是很大的情况
	//readFileByIoUtils(path)

	//写入文件
	//openFile(writePath)

	// 追加内容
	//appendContent(writePath)

	//拷贝图片
	//copyImage(srcImagePath, dstImagePath)

	//判断文件路径
	//exists, _ := PathExists(path)
	//fmt.Println(exists)
}

func readFileByIoUtils(path string) {
	content, err := ioutil.ReadFile(path)
	if err != nil {
		fmt.Println("出错了")
	} else {
		fmt.Println(string(content))
	}
}

func readFileByBuffer(path string) {
	file, err := os.Open(path)
	if err != nil {
		fmt.Println("close file err:", err)
	}
	defer file.Close()
	read := bufio.NewReader(file)
	for {
		str, err := read.ReadString('\n')
		if err == io.EOF {
			break
		}
		fmt.Print(str)
	}
	if err != nil {
		fmt.Println("close file err:", err)
	}
}

func openFile(writePath string) {
	file, err := os.OpenFile(writePath, os.O_WRONLY|os.O_TRUNC, 0666)
	if err != nil {
		fmt.Println("open file failed ", err)
		return
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	for i := 0; i < 10; i++ {
		writer.WriteString(fmt.Sprintf("这是第- %d -次输入..\n", i+1))
	}
	writer.Flush()
}

func appendContent(writePath string) {
	file, err := os.OpenFile(writePath, os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("open file failed ", err)
		return
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	for i := 0; i < 2; i++ {
		writer.WriteString(fmt.Sprintf("追加的内容，第%d行\n", i+1))
	}
	writer.Flush()
}

func copyImage(srcPath, destPath string) {
	srcFile, _ := os.Open(srcPath)
	//关闭文件
	defer srcFile.Close()
	reader := bufio.NewReader(srcFile)
	dstFile, _ := os.OpenFile(destPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	defer dstFile.Close()
	writer := bufio.NewWriter(dstFile)
	io.Copy(writer, reader)
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
